package com.movecar.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movecar.R;
import com.movecar.model.FriendApplyBean;
import com.movecar.model.GroupBean;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.BitMapUtil;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.utils.imageloader.Constants;
import com.movecar.widget.CustomProgressDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 
 * 
 * @author Zhao.JQ
 * 
 */
public class FriendApplyActivity extends Activity implements OnClickListener {

	private ListView mListView;
	private ArrayList<FriendApplyBean> DataList = new ArrayList<FriendApplyBean>();
	private CustomProgressDialog progressDialog = null;
	private ImageLoader imageLoader = null;
	private LinearLayout main_linear, list_linear;

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.friends_apply);
		initView();
	}

	private void initView() {
		imageLoader = ImageLoader.getInstance();
		//imageLoader.init(Constants.imageLoaderConfiguration(this));

		Button back = (Button) findViewById(R.id.btn_left);
		back.setBackgroundResource(R.drawable.btn_back);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		mListView = (ListView) findViewById(R.id.mListView);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("好友申请");

		jsonData();

	}

	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.btn_left:
			finish();
			break;

		default:
			break;
		}

	}

	@SuppressWarnings("unchecked")
	private void jsonData() {

		startProgressDialog();
		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryApplyFriendListNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				String result = (String) object;
				Type type = new TypeToken<List<FriendApplyBean>>() {
				}.getType();
				Gson gson = new Gson();
				stopProgressDialog();
				try {
					DataList = gson.fromJson(result, type);
				} catch (Exception e) {
					return;
				}

				if (DataList == null) {
					Toast.makeText(getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
					return;
				} else {

					if (DataList.size() != 0) {
						DataAdapter dataAdapter = new DataAdapter(FriendApplyActivity.this, DataList);
						mListView.setAdapter(dataAdapter);
					}

				}

			}

			@Override
			public void onFail(String exception) {

				stopProgressDialog();
				Alert.error(FriendApplyActivity.this,"与服务器连接失败，请检查网络");

			}
		}, GroupBean.class, AppConfig.USER).execute(params);
	}

	class DataAdapter extends BaseAdapter {

		private LayoutInflater inflater;
		private ViewHolder viewHolder = null;
		private ArrayList<FriendApplyBean> dataList;

		DataAdapter(Activity activity, ArrayList<FriendApplyBean> dataList) {

			this.dataList = dataList;
			inflater = LayoutInflater.from(activity);
		}

		@Override
		public int getCount() {

			return dataList.size();
		}

		@Override
		public Object getItem(int arg0) {

			return dataList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {

			return arg0;
		}

		@Override
		public View getView(final int position, View view, ViewGroup arg2) {

			if (view == null) {
				viewHolder = new ViewHolder();
				view = inflater.inflate(R.layout.friends_apply_item, null);

				viewHolder.userNickName = (TextView) view.findViewById(R.id.userName);
				viewHolder.icon = (ImageView) view.findViewById(R.id.userImg);
				viewHolder.content = (TextView) view.findViewById(R.id.content);
				viewHolder.btn_ok = (Button) view.findViewById(R.id.btn_ok);
				// viewHolder.btn_ok.setId(position);
				viewHolder.btn_ok.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						startProgressDialog();
						friendApply(dataList.get(position).getFriendId(), "0");
					}
				});
				viewHolder.btn_refuse = (Button) view.findViewById(R.id.btn_refuse);
				viewHolder.btn_refuse.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						startProgressDialog();
						friendApply(dataList.get(position).getFriendId(), "1");
					}
				});

				view.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) view.getTag();
			}
			String nickName = dataList.get(position).getNickname();

			viewHolder.userNickName.setText(nickName);

			if (TextUtils.isEmpty(dataList.get(position).getIcon())) {
				viewHolder.icon.setImageBitmap(BitMapUtil.getRoundedCornerBitmap(BitMapUtil
						.drawableToBitmap(getResources().getDrawable(R.drawable.default_user_photo))));

			} else {
				if (dataList.get(position).getIcon().contains("default")) {
					imageLoader.displayImage(AppConfig.HOST + dataList.get(position).getIcon(), viewHolder.icon,
							Constants.image_display_options);
				} else {
					imageLoader.displayImage(AppConfig.HOST + dataList.get(position).getIcon(), viewHolder.icon,
							Constants.image_display_options_conner);
				}

			}
			viewHolder.content.setText(dataList.get(position).getContent());
			return view;
		}

		class ViewHolder {

			TextView userNickName, content;
			ImageView icon;
			Button btn_ok, btn_refuse;
		}
	}

	@SuppressWarnings("unchecked")
	private void friendApply(String friendId, String strFlag) {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "prFriendNew3")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("friendId", friendId));
		params.add(new BasicNameValuePair("strFlag", strFlag));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				String result = (String) object;
				if ("0".equals(result)) {

					Toast.makeText(getApplicationContext(), "操作成功", Toast.LENGTH_SHORT).show();
					finish();
				} else {
					stopProgressDialog();

					Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void onFail(String exception) {

				Alert.error(FriendApplyActivity.this,"与服务器连接失败，请检查网络");

			}
		}, GroupBean.class, AppConfig.USER).execute(params);
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
}
